/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mdp.lab;

import java.util.*;

/**
 *
 * @author Oleg
 */
public class RequestProcessor {
    
    private final Index index = new Index();
    
    public Response process(Request req) {
        //String[][] responseValues = new String[req.getSecurityIds().size()][req.getFields().size()];
        Map<String, String[]> responseValues = new HashMap<>();
        Map<String, Set<String>> missingFieldsToSecurityIds = new HashMap<>();
        
        final Response response = new Response();
        
        for (String securityId : req.getSecurityIds()) {
            final Map<String, String> values = index.getValues(securityId);
            Set<String> missingFieldsForSecurityIdSet = null;
            if( values != null && values.size() > 0) {
                final String[] responseValuesForSecurity = new String[req.getFields().size()];
                int fieldNumber = 0;
                for (String field : req.getFields()) {
                    fieldNumber++;
                    final String value = values.get(field);
                    if( value != null ) {
                        responseValuesForSecurity[fieldNumber] = value;
                    } else {
                        if ( missingFieldsForSecurityIdSet == null ) {
                            missingFieldsForSecurityIdSet = new  TreeSet<>();
                        }
                        missingFieldsForSecurityIdSet.add(field);
                    }
                }
                responseValues.put(securityId, responseValuesForSecurity);
            } else {
                missingFieldsForSecurityIdSet = new TreeSet<>(req.getFields());
            }
            if( missingFieldsForSecurityIdSet != null) {
                String fieldsKey = fieldSetToString(missingFieldsForSecurityIdSet);
                Set<String> securityIds = missingFieldsToSecurityIds.get(fieldsKey);
                if( securityIds == null) {
                    securityIds = new HashSet<>();
                }
                securityIds.add(securityId);
            }            
        }
        
        return response;
    }
    
    static String fieldSetToString(Set<String> fields) {
        StringBuilder sb = new StringBuilder();
        for (String field : fields) {
            sb.append(field).append("|");
        }
        final String result = sb.toString();
        return result.substring(0, result.length()-2);
    }
}
